package com.apes.fa.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fa.model.FaCard;
import com.apes.fa.model.InventoryTransferAsset;
import com.apes.fa.model.InventoryTransferAssetItem;
import com.apes.fa.respository.InventoryTransferAssetItemRepository;
import com.apes.fa.respository.InventoryTransferAssetRepository;
import com.apes.fa.respository.TransferAssetItemRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Tools;
import com.apes.pi.service.PiManager;
import com.apes.scm.account.account.model.AccountingMethod;
import com.apes.scm.account.account.model.InventoryBatch;
import com.apes.scm.account.account.model.InventoryMode;
import com.apes.scm.account.account.model.Stock;
import com.apes.scm.account.account.repository.InventoryBatchRepository;
import com.apes.scm.account.account.repository.StockRepository;
import com.apes.scm.account.account.service.InventoryService;
import com.apes.scm.account.account.service.ProductAccountService;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.*;
import com.apes.scm.masterdata.product.repository.ProductRepository;
import com.apes.scm.stock.transfer.model.Pick;
import com.apes.scm.stock.transfer.model.PickItem;
import com.apes.scm.stock.transfer.repository.PickRepository;
import com.apes.scm.voucher.model.Voucher;
import com.apes.scm.voucher.model.VoucherItem;
import com.apes.scm.voucher.service.BusinessType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.scm.stock.transfer.service
 * @ClassName: InventoryTransferAssetService
 * @Author: pyb
 * @Description: 库存转资产服务
 * @CreateTime: 2021-04-23 15:53
 * @Version: 1.0
 */
@Service("inventoryTransferAssetService")
public class InventoryTransferAssetService extends DomainService {
    @Autowired
    InventoryTransferAssetRepository inventoryTransferAssetRepository;
    @Autowired
    InventoryBatchRepository inventoryBatchRepository;
    @Autowired
    ProductAccountService productAccountService;
    @Autowired
    InventoryService inventoryService;
    @Autowired
    ProductRepository productRepository;
    @Autowired
    StockRepository stockRepository;
    @Autowired
    FaCardService faCardService;
    @Autowired
    FaCardAccountService faCardAccountService;
    @Autowired
    PiManager piManager;
    @Autowired
    private InventoryTransferAssetItemRepository inventoryTransferAssetItemRepository;

    /**
     * 保存
     *
     * @param request
     * @return
     */
    public InventoryTransferAsset save(SimpleRequest request) {
        InventoryTransferAsset inventoryTransferAsset = request.getO(InventoryTransferAsset.class);
        inventoryTransferAsset.setState("sent");
        InventoryTransferAsset transferAsset = inventoryTransferAssetRepository.saveAndFlush(inventoryTransferAsset);
        //更新库存 批次
        updateProductAvailableAndBatch(transferAsset, false, "库存转资产保存");
        return transferAsset;
    }

    /**
     * 编辑
     *
     * @param request
     * @return
     */
    public InventoryTransferAsset update(SimpleRequest request) {
        InventoryTransferAsset inventoryTransferAsset = request.getO(InventoryTransferAsset.class);
        //明细检查
//        check(inventoryTransferAsset.getInventoryTransferAssetItems());
        //还原库存 批次
        updateProductAvailableAndBatch(inventoryTransferAsset, true, "库存转资产修改还原");

        // 处理被删除的明细
        List itemIds = inventoryTransferAsset.getInventoryTransferAssetItems().stream().filter(item -> StringUtils.hasText(item.getId())).map(item -> item.getId()).collect(Collectors.toList());
        List<InventoryTransferAssetItem> findDeleteProItems = inventoryTransferAssetItemRepository.findDeleteProItem(inventoryTransferAsset.getId(), itemIds);
        this.handleDeleteProStock(inventoryTransferAsset, findDeleteProItems, "库存转资产修改还原");

        InventoryTransferAsset transferAsset = inventoryTransferAssetRepository.saveAndFlush(inventoryTransferAsset);
        //更新库存 批次
        updateProductAvailableAndBatch(transferAsset, false, "库存转资产编辑");
        return transferAsset;
    }

    private void handleDeleteProStock(InventoryTransferAsset inventoryTransferAsset, List<InventoryTransferAssetItem> items, String note) {
        items.forEach(item -> {
            if (LogicalUtil.notIn(item.getProduct().getType(), "aut")) {
                // 减少（增加）商品可用数
                productAccountService.setProductAvailable(item.getProduct(), inventoryTransferAsset.getLocation(),
                        item.getUom(), item.getProductTransferQty(), inventoryTransferAsset.getInnerBusinessType(), inventoryTransferAsset.getInnerBusinessKey(),
                        String.valueOf(item.getId()), note, inventoryTransferAsset.getCompany());
            }

            // 增加（减少）商品价值（商品批次） 的冻结数量
            // 查询批次信息
            InventoryBatch inventoryBatch = inventoryBatchRepository.findOne(item.getInventoryBatch().getId());
            inventoryService.changeFrostQty(inventoryBatch, item.getUom(), item.getProductTransferQty(), inventoryTransferAsset.getCompany(), inventoryTransferAsset.getInnerBusinessType(), inventoryTransferAsset.getInnerBusinessKey(),
                    String.valueOf(item.getId()), note);
        });

    }

    /**
     * 删除成功
     *
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        InventoryTransferAsset inventoryTransferAsset = request.getO(InventoryTransferAsset.class);
        //明细检查
//        check(inventoryTransferAsset.getInventoryTransferAssetItems());
        //还原库存 批次
        updateProductAvailableAndBatch(inventoryTransferAsset, true, "库存转资产删除还原");
        inventoryTransferAssetRepository.delete(inventoryTransferAsset.getId());
        return "删除成功";
    }

//    public void check(List<InventoryTransferAssetItem> inventoryTransferAssetItems){
//        for (InventoryTransferAssetItem item : inventoryTransferAssetItems) {
//            if ("W02".equals(item.getFaCategory().getId().substring(0,3)) && item.getPriceUnit() > 1500){
//                throw new RuntimeException(String.format("[%s]商品不可进行库存转资产，有疑问请联系财务中心对接人", item.getProduct().getName()));
//            }
//        }
//    }

    /**
     * 审核并生成发货单
     *
     * @param request
     * @return
     */
    public InventoryTransferAsset approve(SimpleRequest request) {
        InventoryTransferAsset inventoryTransferAsset = request.getO(InventoryTransferAsset.class);
        inventoryTransferAsset.setState("approve");
        inventoryTransferAsset.setApproveUid(this.getPerson(request));
        inventoryTransferAsset.setDateApprove(new Date());
        InventoryTransferAsset asset = inventoryTransferAssetRepository.saveAndFlush(inventoryTransferAsset);
        createPickOrder(inventoryTransferAsset);
        return asset;
    }


    /**
     * 创建交货单
     *
     * @param inventoryTransferAsset
     * @return
     */
    private Pick createPickOrder(InventoryTransferAsset inventoryTransferAsset) {
        //创建拣配单
        Pick pick = new Pick();
        Enumeration enumeration = new Enumeration();
        enumeration.setId("one");
        //一次性交货
        pick.setMoveType(enumeration);
        // 公司为发货仓的公司
        pick.setCompany(inventoryTransferAsset.getCompany());
        //合作伙伴为公司的客户角色
        pick.setPartner(inventoryTransferAsset.getCompany().getParty().getPatyRoleByType("Customer"));
        pick.setLocation(inventoryTransferAsset.getLocation());
        pick.setOrigin(inventoryTransferAsset.getId());
        pick.setOriginBusinessType(inventoryTransferAsset.getInnerBusinessType());
        // 交货类型： 交货
        pick.setOperation("deliver");
        // 注入场景
        pick.setScene(inventoryTransferAsset.getScene());
        pick.setPickItems(inventoryTransferAsset.getInventoryTransferAssetItems().stream().map(item -> {
            PickItem pickItem = new PickItem();
            pickItem.setProduct(item.getProduct());
            pickItem.setUom(item.getUom());
            pickItem.setOrderedQty(item.getProductTransferQty());
            pickItem.setProductUomQty(item.getProductTransferQty());
            pickItem.setOriginLine(item.getId());
            return pickItem;
        }).collect(Collectors.toSet()));
        // 创建交货单
        EventUtil.sendSynEvent(this, "event:stock.pick.save", pick);
        return pick;
    }


    /**
     * 功能：处理交货完成事件
     */
    @Listener(topic = "event:stock.pick.delivery")
    public void delivery(SimpleRequest request) {
        JSONObject param = request.getJO();
        if (!param.getString("originBusinessType").equals(InventoryTransferAsset.class.getSimpleName())) return;
        InventoryTransferAsset inventoryTransferAsset = inventoryTransferAssetRepository.findOne(param.getString("origin"));
        if ("deliver".equals(param.getString("operation"))) {
            //创建凭证
            Voucher voucher = new Voucher();
            // 主表信息
            voucher.setScene(inventoryTransferAsset.getScene());
            voucher.setCompany(inventoryTransferAsset.getCompany());
            voucher.setDept(inventoryTransferAsset.getDept());
            voucher.setClerk(inventoryTransferAsset.getClerk());
            voucher.setPartner(inventoryTransferAsset.getCompany().getParty().getPatyRoleByType("Customer"));
            voucher.setInventoryMode(InventoryMode.IM_OWN);
            voucher.setAccountingMethod(AccountingMethod.AM_PURCHASE);
            voucher.setBusinessType(BusinessType.SALE_ORDER);
            voucher.setOrigin(inventoryTransferAsset.getId());
            voucher.setOriginBusinessType(inventoryTransferAsset.getInnerBusinessType());
            voucher.setSource(param.getString("pickId"));
            voucher.setSourceBusinessType(Pick.class.getSimpleName());
            // 从表信息
            voucher.setVoucherItems(getAssetVoucherItems(inventoryTransferAsset, SpringManager.getBean(PickRepository.class).findOne(param.getString("pickId"))));
            //写入凭证
            invoke("voucher.create", MapUtil.mapped(voucher));
            //生成资产卡片
//            generateAssetCards(inventoryTransferAsset);
            //生成资产卡片2.0
            generateFaCard(inventoryTransferAsset,request);

        }
    }

    /**
     * 生成资产卡片2.0
     */
    public void generateFaCard(InventoryTransferAsset inventoryTransferAsset,SimpleRequest request) {
        inventoryTransferAsset.setState("done");

        inventoryTransferAsset.getInventoryTransferAssetItems().forEach(item -> {

            for (double i = 0.0; i < item.getProductTransferQty(); i++) {

                FaCard faCard = new FaCard();
                Product product = new Product();
                FaCategory faCategory = new FaCategory();
                PartyRole company = new PartyRole();
                Dept dept = new Dept();

                faCard.setBusinessName("资产卡片建卡");//单据类型名称
                faCard.setSourceBusinessType("KCZZC");//来源单据类型
                faCard.setSourceBusinessKey(inventoryTransferAsset.getInnerBusinessKey());//来源单据号码
                faCard.setSourceBusinessName("库存转资产");//来源单据名称
                faCategory.setId(item.getFaCategory().getInnerBusinessKey());//资产类别id
                product.setId(item.getProduct().getId());//商品ID
                product.setName(item.getProduct().getName());//商品名称
                faCard.setMeasurementUnit(item.getUom().getName());//计量单位名称
                faCard.setOriginalValue(item.getPriceUnit());//原值
                faCard.setUseYear(item.getFaCategory().getYear());//使用年限
                company.setId(inventoryTransferAsset.getCompany().getId());//公司id
                String typeId = item.getFaCategory().getAssetType().getId();
                faCard.setFaType(typeId.equals("fixedAssets") ? "固定资产" : (typeId.equals("low") ? "低值易耗" : (typeId.equals("materials") ? "材料物质" : (typeId.equals("gift") ? "礼品" : "固定资产"))));//固定资产类型
                faCard.setQuantity(1);//数量
                faCard.setDepreciation(0.0);//折旧
                faCard.setResponsiblePerson(this.getPerson(request));//记账人
                faCard.setPurchaseDate(new Date());//购置日期
                faCard.setEnableDate(new Date());//启用日期
                faCard.setUseMonth(item.getFaCategory().getMonth());//使用月限
                faCard.setEstimatedResidualValueRate(item.getFaCategory().getNetResidualValueRate());//预计残值率
                faCard.setDepreciationMethod(item.getFaCategory().getDepreciationMethod());//折旧方法
                faCard.setAnnualDepreciationRate(0.0);//年折旧率
                faCard.setMonthlyDepreciationRate(0.0);//月折旧率
                faCard.setFaStatus("1");//资产状态
                dept.setId(inventoryTransferAsset.getDept().getId());//部门id
                dept.setName(inventoryTransferAsset.getDept().getName());//部门名称
                faCard.setFaSource("购入");//资产来源
                faCard.setFaWhereabouts(null);//资产去向
                faCard.setTransferInUnit(null);//转入单位
                faCard.setTransferUnit(null);//转出单位
                faCard.setNote("库存转资产自动生成卡片(单号:" + inventoryTransferAsset.getId() + ")");
                faCard.setEvaluationMark("0");//评估标志
                faCard.setEvaluationOriginalValue(0.0);//评估原值
                faCard.setDepreciationMark(faCard.getFaType().equals("固定资产"));//折旧标记 固定资产才有折旧标记
                faCard.setRemainingDepreciationMonth(item.getFaCategory().getYear() * 12 + item.getFaCategory().getMonth());//剩余折旧月
                faCard.setCreator(inventoryTransferAsset.getCreator());// 制单人
                faCard.setCreateDate(inventoryTransferAsset.getCreateDate());
                faCard.setApproveUid(inventoryTransferAsset.getApproveUid());//审核人
                faCard.setApproveDate(inventoryTransferAsset.getDateApprove());//审核时间
                faCard.setBusinessState("0");//单据状态
                faCard.setResponsiblePerson(inventoryTransferAsset.getApproveUid());//负责人
                faCard.setCustodian(this.getPerson(request));//保管人
                faCard.setUsePlace(null);//使用地点
                faCard.setProduct(product);
                faCard.setDept(dept);
                faCard.setUseDept(dept);
                faCard.setFaCategory(faCategory);
                faCard.setCompany(company);
                faCard.setCustodian(inventoryTransferAsset.getApproveUid());//保管人
                faCard.setApproveUid(inventoryTransferAsset.getApproveUid());
                faCardService.beforeSave(faCard);

            }
        });

        inventoryTransferAssetRepository.saveAndFlush(inventoryTransferAsset);

    }

    /**
     * 生成资产卡片
     *
     * @param inventoryTransferAsset
     */
    public void generateAssetCards(InventoryTransferAsset inventoryTransferAsset) {
        inventoryTransferAsset.getInventoryTransferAssetItems().forEach(item -> {
            //生成资产卡片
            JSONObject zckp = new JSONObject();
            zckp.put("DJLXID", "KP0");
            zckp.put("DJLXMC", "资产卡片建卡");//单据类型名称
            zckp.put("LYDJLX", "KCZZC");//来源单据类型
            zckp.put("LYDJHM", inventoryTransferAsset.getInnerBusinessKey());//来源单据号码
            zckp.put("LYDJMC", "库存转资产-赋能");//来源单据名称
            zckp.put("ZCFLID", item.getFaCategory().getInnerBusinessKey());//资产类别id
            zckp.put("SPID", item.getProduct().getId());//商品ID
            zckp.put("SPMC", item.getProduct().getName());//商品名称
            zckp.put("PLID", item.getProduct().getClassify().getId());//商品分类id
            zckp.put("PLMC", item.getProduct().getClassify().getName());//商品分类名称
            zckp.put("PPID", item.getProduct().getBrand().getId());//品牌id
            zckp.put("PPMC", item.getProduct().getBrand().getName());//品牌名称
            zckp.put("JLDW", item.getUom().getName());//计量单位名称

            zckp.put("SL", item.getProductTransferQty());//数量

            zckp.put("YZ", item.getPriceUnit());//原值
            zckp.put("SYNX", item.getFaCategory().getYear());//使用年限
            zckp.put("GSID", inventoryTransferAsset.getCompany().getId());//公司id 无
            String typeId =  item.getFaCategory().getAssetType().getId();
            zckp.put("GDZCLX", typeId.equals("fixedAssets") ? "0" : (typeId.equals("low") ? "1" : (typeId.equals("materials") ? "2" : (typeId.equals("gift") ? "3" : "0"))));//固定资产类型
            zckp.put("SL", 1);//数量
            zckp.put("ZJ", 0);//折旧
            zckp.put("JZR", inventoryTransferAsset.getCreator());//记账人
            zckp.put("GZRQ", "SYSDATE");//购置日期
            zckp.put("QYRQ", "SYSDATE");//启用日期
            zckp.put("SYYX", 0);//使用月限
            zckp.put("YJCZL", 0.05);//预计残值率
            zckp.put("ZJFF", 0);//折旧方法
            zckp.put("NZJL", 0);//年折旧率
            zckp.put("YZJL", 0);//月折旧率
            zckp.put("ZCZT", 1);//资产状态
            zckp.put("BMID", inventoryTransferAsset.getDept().getId());//部门id
            zckp.put("BMMC", inventoryTransferAsset.getDept().getName());//部门名称
            Store store = SpringManager.getBean(StoreRepository.class).findOne(inventoryTransferAsset.getDept().getId());
            zckp.put("CBZXID", store.getBranchEntry().getId());//开店申请
            zckp.put("CBZXMC", store.getBranchEntry().getName());//开店申请
            zckp.put("MDID", store.getCode());//门店id
            zckp.put("MDMC", store.getName());//门店名称
            zckp.put("ZCLY", 1);//资产来源
            zckp.put("ZCQX", null);//资产去向
            zckp.put("ZRDW", null);//转入单位
            zckp.put("ZCDW", null);//转出单位
            zckp.put("BZ", "库存转资产自动生成卡片(单号:" + inventoryTransferAsset.getId() + ")");
            zckp.put("PGBJ", 0);//评估标志
            zckp.put("PGYZ", 0);//评估原值
            zckp.put("ZJBJ", 0);//折旧标记
            zckp.put("SYZJY", item.getFaCategory().getYear() * 12);//剩余折旧月
            zckp.put("ZDR", inventoryTransferAsset.getCreator()); // 制单人 无
            zckp.put("ZDRQ_SJ", "SYSDATE"); // 制单日期 无
            zckp.put("SHR", null);//审核人 无
            zckp.put("SHRQ_SJ", null);//审核日期 无
            zckp.put("DJZT", 0);//单据状态
            zckp.put("FZR", null);//负责人
            zckp.put("BGR", null);//保管人
            zckp.put("ZJJZ", 0);//折旧价值
            zckp.put("CZY", inventoryTransferAsset.getCreator());//操作员
            zckp.put("JKR", inventoryTransferAsset.getCreator());//借款人
            zckp.put("SYDD", null);//使用地点

            for (int qty = 0; qty < item.getProductTransferQty(); qty++) {
                piManager.synErp("assZckpService.insertAndSh", zckp);
            }
        });
    }

    /**
     * 从表信息
     *
     * @param inventoryTransferAsset
     * @param pick
     * @return
     */
    public Set<VoucherItem> getAssetVoucherItems(InventoryTransferAsset inventoryTransferAsset, Pick pick) {
        Set<VoucherItem> voucherItems = new HashSet();
        Map<String, InventoryTransferAssetItem> assetItemMap = inventoryTransferAsset.getInventoryTransferAssetItems().stream()
                .collect(Collectors.toMap(InventoryTransferAssetItem::getId, Item -> Item));

        pick.getPickItems().forEach(
                pickItem -> {

                    VoucherItem voucherItem = new VoucherItem();
                    InventoryTransferAssetItem orderItem = assetItemMap.get(pickItem.getOriginLine());
                    if (orderItem == null) throw new RuntimeException("未找到库存转资产订单行：" + pickItem.getOriginLine());

                    voucherItem.setTax(orderItem.getProduct().getTax());
                    voucherItem.setOwner(inventoryTransferAsset.getLocation().getCompany());
                    voucherItem.setProduct(pickItem.getProduct());
                    // 设置为销售的单位以及单价
                    voucherItem.setUom(orderItem.getUom());
                    voucherItem.setProductQty(pickItem.getQtyDone());

                    //TODO 含税单价设为0
                    voucherItem.setPriceUnit(0);

                    voucherItem.setOriginItemId(orderItem.getId());
                    voucherItem.setSourceItemId(String.valueOf(pickItem.getId()));
                    voucherItem.setSupplier(null);
                    voucherItem.setInventoryBatch(orderItem.getInventoryBatch());
                    voucherItems.add(voucherItem);
                }
        );
        return voucherItems;
    }


    /**
     * 查找可调拨批次
     *
     * @param request
     * @return
     */
    public Map findInventoryBatch(SimpleRequest request) {
        JSONArray condition = (JSONArray)request.get("condition");
        JSONObject conditionModel = (JSONObject)request.get("conditionModel");
        String productId = (String) condition.getJSONObject(0).get("value");
        String locationId = (String) conditionModel.getJSONObject("location").get("id");
        String companyId = (String) conditionModel.getJSONObject("company").get("id");
        //判断商品是否支持转资产
        Product product = productRepository.findOne(productId);
        if (LogicalUtil.in(product.getType(), "aut")) {
            throw new RuntimeException("服务商品不支持转资产");
        }
        if (Tools.isNull(product.getFaCategory())) {
            throw new RuntimeException(String.format("[%s]商品不可进行库存转资产，有疑问请联系财务中心对接人", product.getName()));
        }
        // 查找商品库存帐的可用数是否大于0
        Stock stock = stockRepository.findFirstByProductIdAndLocationIdAndUsableQtyGreaterThan(productId, locationId, 0);
        // 获取可用数
        double usableQty = Optional.ofNullable(stock).map(Stock::getUsableQty).orElseThrow(() -> new RuntimeException("该商品无可用库存!"));

        // 获取结存大于冻结的批次
        Page<InventoryBatch> inventoryBatchPage = inventoryBatchRepository.findReturnableByCompanyIdAndProductId(companyId, productId, PageRequest.of(request.get("page"), request.get("size")));
        inventoryBatchPage.getContent().forEach(
                (inventoryBatch) -> {
                    inventoryBatch.setUsableQty(usableQty);
                    inventoryBatch.setCanReturnQty(Math.min(usableQty, inventoryBatch.getBalanceQty() - inventoryBatch.getFrostQty()));
                }
        );

        Map mapper = MapUtil.mapped(inventoryBatchPage);
        if (inventoryBatchPage.getContent().size() == 0) {
            mapper.put("msg", "未找到可转资产的商品数据！");
        }

        ((List<Map>) mapper.get("content")).forEach(batch -> {
            batch.put("faCategory", MapUtil.mapped(product.getFaCategory()));
        });
        return mapper;

    }

    /**
     * 更新商品库存可用数，批次表冻结数量
     *
     * @param inventoryTransferAsset
     * @param flag true: 减少、false：增加
     * @param note
     */
    private void updateProductAvailableAndBatch(InventoryTransferAsset inventoryTransferAsset, boolean flag, String note) {
        inventoryTransferAsset.getInventoryTransferAssetItems().forEach(item -> {
            //转资产数量
            double changeQty = 0.0;
            if (!flag) {
                changeQty = -1 * Math.abs(item.getProductTransferQty());
            } else {
                // 修改需要找原来的历史数据
                if (StringUtils.hasText(item.getId())) changeQty = Math.abs(inventoryTransferAssetItemRepository.findOne(item.getId()).getProductTransferQty());
            }

            if (changeQty == 0) return;
            if (LogicalUtil.notIn(item.getProduct().getType(), "aut")) {
                // 减少（增加）商品可用数
                productAccountService.setProductAvailable(item.getProduct(), inventoryTransferAsset.getLocation(),
                        item.getUom(), changeQty, inventoryTransferAsset.getInnerBusinessType(), inventoryTransferAsset.getInnerBusinessKey(),
                        String.valueOf(item.getId()), note, inventoryTransferAsset.getCompany());
            }


            // 增加（减少）商品价值（商品批次） 的冻结数量
            // 查询批次信息
            InventoryBatch inventoryBatch = inventoryBatchRepository.findOne(item.getInventoryBatch().getId());
            inventoryService.changeFrostQty(inventoryBatch, item.getUom(), -1 * changeQty, inventoryTransferAsset.getCompany(), inventoryTransferAsset.getInnerBusinessType(), inventoryTransferAsset.getInnerBusinessKey(),
                    String.valueOf(item.getId()), note);
        });
    }
}
